package com.keyboardr.gamerater.fragment;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;

import com.keyboardr.gamerater.R;
import com.keyboardr.gamerater.RaterActivity;
import com.keyboardr.gamerater.adapter.GameAdapter;
import com.keyboardr.gamerater.model.Player;

public class GamesFragment extends ListFragment {

	private Player filter;

	/**
	 * @return the filter
	 */
	public Player getFilter() {
		return filter;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.games, menu);
	}

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		try {
			menu.findItem(R.id.undoLastGame).setVisible(
					((RaterActivity) getActivity()).getSelectedGroup()
							.getGames().size() > 0);
		} catch (NullPointerException e) { // Caught because this code can be
											// run before the Groups are
											// initialized when using holo
											// theme, but will be run again
											// after groups are initialized
			e.printStackTrace();
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.undoLastGame:
			((RaterActivity) getActivity()).getSelectedGroup().revertLastGame();
			((RaterActivity) getActivity()).itemsChanged();
			((RaterActivity) getActivity()).save();
			break;
		}
		return false;
	}

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		if (bundle != null
				&& bundle.getString("filter") != null
				&& ((RaterActivity) getActivity()).getSelectedGroup() != null
				&& bundle.getInt("lastGroupSize", -1) == ((RaterActivity) getActivity())
						.getSelectedGroup().getPlayers().size()) {
			try {
				filter = new Player(new JSONObject(bundle.getString("filter")));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			bundle.getInt("lastGroupSize", -1);
		}
		setHasOptionsMenu(true);
	}

	@Override
	public void onStart() {
		super.onStart();
		setListAdapter(new GameAdapter((RaterActivity) getActivity(), filter));
		getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
	}

	@Override
	public void onSaveInstanceState(Bundle bundle) {
		if (filter != null) {
			bundle.putString("filter", filter.toJSON().toString());
			bundle.putInt("lastGroupSize", ((RaterActivity) getActivity())
					.getSelectedGroup().getPlayers().size());
		}
	}

	public void setFilter(Player filter) {
		if (null == filter || filter.equals(this.filter)) {
			this.filter = null;
		} else {
			this.filter = filter;
		}
		GameAdapter gameAdapter = (GameAdapter) getListAdapter();
		if (gameAdapter != null) {
			gameAdapter.setGameFilter(this.filter);
		}
	}
}
